import XLSX from 'xlsx';
import { getCategoryList, getStudentAgeList } from '@/api/course';

export const getSheetData = (sheetData, schemaMap) => {
  const header = schemaMap.map((item) => item.label);
  const schema = schemaMap.map((item) => item.prop);
  const sheetArray = sheetData.map((rowData) => schema.map((item) => rowData[item]));
  return [header, ...sheetArray];
};

export const saveExcel = ({ sheetData, schemaMap, fileName }) => {
  const sheetArray = getSheetData(sheetData, schemaMap);
  const workSheet = XLSX.utils.aoa_to_sheet(sheetArray);
  const workbook = XLSX.utils.book_new();
  workbook.SheetNames.push(fileName);
  workbook.Sheets[fileName] = workSheet;
  const wopts = {
    bookType: 'xlsx', bookSST: false, type: 'array', compression: true,
  };
  XLSX.writeFile(workbook, `${fileName}.xlsx`, wopts);
};

export const generateRandomString = () => {
  const length = 5;
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;

  return Array(length)
    .fill(null)
    .map(() => characters.charAt(Math.floor(Math.random() * charactersLength)))
    .join('');
};

export const generateFileName = (name) => {
  const dotIndex = name.lastIndexOf('.');
  const ext = name.substring(dotIndex + 1);
  const timestamp = Date.now();
  return `${timestamp}-${generateRandomString()}.${ext}`;
};

export const getFirstCategoryList = async () => {
  const { list } = await getCategoryList({
    pageNum: 0,
    pageSize: 10,
    level: 1,
    name: '',
  });
  return list.map((item) => ({
    value: item.id,
    label: item.name,
  }));
};

export const getSecondCategoryList = async () => {
  const { list } = await getCategoryList({
    pageNum: 0,
    pageSize: 100,
    level: 2,
    name: '',
  });
  return list.map((item) => ({
    value: item.id,
    label: item.name,
    parentId: item.parentId,
  }));
};

export const getStudentAgeOptions = async () => {
  const { list } = await getStudentAgeList({
    pageNum: 0,
    pageSize: 100,
  });
  return list.map((item) => {
    const { id, minVal, maxVal } = item;
    return {
      value: id,
      label: `${minVal} - ${maxVal}岁`,
    };
  });
};
